package com.algorithm2;

import java.util.Arrays;

public class HeapSort3 {

    private static void buildHeap(int[] a,int n){
        for(int i=(n/2);i>=0;--i){
            heapify(a,n,i);
        }
    }

    public static void heapify(int[] a,int n,int i){
            int maxPos = i;
            int left = 2*i+1;
            int right = 2*i+2;
            if(left<n && a[left]>a[maxPos]){
                maxPos = left;
            }
            if(right<n && a[right]>a[maxPos]){
                maxPos = right;
            }
            if(maxPos!=i){
                swap(a,maxPos,i);
                heapify(a,n,maxPos);
            }
        System.out.println("i为："+"-->"+i +"-->"+ Arrays.toString(a));

    }
    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }


    public static void main(String[] args){
        int[] array = new int[]{8, 9, 3,10, 2, 4, 5, 6, 7, 1};
        buildHeap(array,array.length);
        System.out.println("构建堆:" + Arrays.toString(array));
    }
}
